package com.jfinal.web.interceptor;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.JFinal;
import com.jfinal.web.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * 捕获所有异常
 *
 * @author Chen
 */
public class ExceptionInterceptor implements Interceptor {

    private static final Logger logger = LoggerFactory.getLogger(ExceptionInterceptor.class);

    @Override
    public void intercept(Invocation ai) {

        ai.getController().getResponse().setCharacterEncoding("UTF-8");
        try {
            ai.invoke();
        } catch (IllegalArgumentException e) {
            logger.error(e.getMessage(), e);
            ai.getController().renderJson(Response.fail("非法参数"));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            ai.getController().renderJson(Response.fail("服务器异常"));
            if (JFinal.me().getConstants().getDevMode()) {
                try {
                    e.printStackTrace(ai.getController().getResponse().getWriter());
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }

        }
    }


}
